package com.wwu.common.utils;

import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;

/**
 * @author 一蓑烟雨
 * @version 1.0.0
 * @date 2023-05-31 21:05
 */
public class IpUtils {
    /** 地址常亮 */
    public  static  final  String  IP_UNKNOWN = "unknown";

    /**
     * 获取客户端真实ip地址
     * @param request
     * @return java.lang.String
     * @author 一蓑烟雨
     * @date 2023/5/31 21:09
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = null;
        try {
            ip = request.getHeader("x-forwarded-for");
            if (!StringUtils.hasText(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (!StringUtils.hasText(ip) || ip.length() == 0 || IP_UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (!StringUtils.hasText(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (!StringUtils.hasText(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (!StringUtils.hasText(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ip;
    }

    /**
     * 获取主机名
     * @param request
     * @return java.lang.String
     * @author 一蓑烟雨
     * @date 2023/5/31 21:14
     */
    public static String getRemoteHost(HttpServletRequest request) {
        try {
              return  request.getRemoteHost();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "主机名获取失败";
    }
}
